import React, {useEffect, useState} from "react";
import {Input, Tree} from 'antd';
import {DownOutlined} from "@ant-design/icons";
import {deptTreeSelect} from "@/api/system/dept.ts";
import {getExpandedKeys, handleTree, ParameterFiltering} from "@/utils/Z.ts";


// 定义组件的 props 类型
interface MyComponentProps {
    handleNodeTree: (e: any) => void;
}

const ThreeComponentView: React.FC<MyComponentProps> = ({handleNodeTree}) => {

    // 原始的树形数据储存，不做处理
    const [deptOptions, setDeptOptions] = useState([])
    //展示的树形数据，可以处理
    const [treeOptions, setTreeOptions] = useState<any[]>([])
    const [expandedKeys, setExpandedKeys] = useState<any[]>([])
    useEffect(() => {
        getDeptTree()

    }, [])

    function setKey(data: any) {
        data.forEach((item: any) => {
            item.key = item.id
            item.title = item.label
            if (item.children && item.children.length !== 0) {
                setKey(item.children)
            }
        })
        return data;
    }

    /** 查询部门下拉树结构 */
    function getDeptTree() {
        deptTreeSelect().then((res:any) => {
            setDeptOptions(setKey(res.data));
            setTreeOptions(setKey(res.data));
            setExpandedKeys(getExpandedKeys(setKey(res.data)));
        });
    }

    //输入框查询过滤树下拉
    function onChange(e: React.ChangeEvent<HTMLInputElement>) {
        const {value} = e.target
        setTreeOptions(ParameterFiltering(deptOptions, value))
        setExpandedKeys(getExpandedKeys(deptOptions))
    }

    function onExpand(newExpandedKeys: any) {
        console.log(newExpandedKeys);
        setExpandedKeys(newExpandedKeys);
    }

    // 点击节点查询对应的参数
    function onSelect(selectedKeys: any, e: { selected: boolean, selectedNodes: any[], node: any, event: string }) {
        handleNodeTree(e)
    }

    return (
        <>
            <div>
                <Input style={{marginBottom: 8}} placeholder="Search" onChange={onChange}/>
            </div>
            <div>
                <Tree
                    showLine
                    switcherIcon={<DownOutlined/>}
                    expandedKeys={expandedKeys}
                    treeData={treeOptions}
                    onExpand={onExpand}
                    onSelect={onSelect}
                />
            </div>
        </>
    )
};
export default ThreeComponentView;
